<template>
  <div class="bankContainer">
    <!--搜索条件区域-->
    <div v-show="$route.name === 'personal'" class="personalSearch">
      <el-row>
        <!--<el-col :span="2">-->
        <!--<div class="grid-content bg-purple searchInputStyle">查询条件：</div>-->
        <!--</el-col>-->
        <el-col :lg="15" :md="20">
          <div class="grid-content bg-purple-light">
            <avue-form
              ref="formPersonal"
              v-model="objForm"
              :option="optionFormData"
              @submit="searchSubmitForm"
            />
          </div>
        </el-col>
        <el-col :lg="7" :md="24">
          <div class="grid-content bg-purple">
            <el-button
              type="primary"
              @click="customerInquiry"
            >客户查询</el-button>
            <el-button
              type="primary"
              @click="verificationFn(0)"
            >密码验证</el-button>
            <el-button
              type="primary"
              @click="verificationFn(1)"
            >短信验证</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="verificationTips">
      <span
        :class="{
          'el-icon-circle-close': this.idPass,
          'color-red': this.idPass,
          'el-icon-circle-check': !this.idPass,
          'color-green': !this.idPass,
        }"
      >{{ this.idCheckTxt }}</span>
    </div>
    <!-- 客户信息 -->
    <informationShow :data="personalInfoData" :option="personalOption" />
    <!-- 面包屑导航 -->
    <el-breadcrumb
      v-show="$route.name !== 'personal'"
      separator-class="el-icon-arrow-right"
      style="padding-left: 0px"
    >
      <el-breadcrumb-item
        :to="{ name: 'personal' }"
      >个人业务</el-breadcrumb-item>
      <el-breadcrumb-item
        v-if="$route.name === 'bussDetail' || $route.name === 'unBussDetail'"
        :to="{ name: 'customeBuss' }"
      >业务信息</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $route.meta.aliasName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 子模块区域 -->
    <div v-show="$route.name === 'personal'" class="sonArea mt10">
      <draggable v-model="listData" @start="drag = true" @end="drag = false">
        <div
          v-for="(item, index) in listData"
          v-if="item.show"
          :key="index"
          class="inlineStyle"
        >
          <div @click="goCreditList(item.routerName)">
            <div :class="[item.imgClass, 'commonIcon']" alt />
            <span>{{ item.name }}</span>
          </div>
        </div>
      </draggable>
    </div>
    <!-- 子模块路由展示 -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
  </div>
</template>
<script>
import informationShow from '@/components/common/informationShow'
import searchInput from '@/components/common/CommonDate'
import ChildDropDown from '@/components/common/DropDownLoad'
import draggable from 'vuedraggable'
import { queryInfo, sendCode } from '@/api/interface'
export default {
  components: {
    // 客户信息展示
    informationShow,
    searchInput,
    ChildDropDown,
    draggable
  },
  data() {
    const _that = this
    // 手机号验证
    const validatePhone = function(rule, value, callback) {
      const phoneReg =
        /^1(3[0-9]|4[01456789]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      if (phoneReg.test(value)) {
        // 手机号验证通过
        callback()
      } else {
        // 手机号验证未通过
        callback(new Error('请输入正确的手机号！'))
      }
    }
    const validateIdCard = function(rule, value, callback) {
      // 身份证
      let idcardReg =
        /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      // 护照
      if (_that.objForm.idType == '17') {
        idcardReg = /^\d{1,}$/
      }
      if (idcardReg.test(value)) {
        if (_that.clickEventFlag) {
          _that.clickEventFlag = false
          _that.accountData = []
          _that.personalInfoData = []
          _that.$store.commit('SET_PERSONALFLAG', false)
          _that.idCheckTxt = '身份验证未通过'
          _that.idPass = true
          _that.allFn('cardNo')
        }
        _that.$refs['formPersonal'].clearValidate()
        callback()
      } else {
        callback(new Error('请输入正确的证件号码！'))
      }
    }
    return {
      // 业务信息列表
      listData: [],
      checkFlag: false,
      // 客户输入信息
      objForm: {},
      optionFormData: {
        emptyBtn: false,
        submitBtn: false,
        menuPosition: 'left',
        column: [
          {
            label: '手机号',
            prop: 'mobileNo',
            appendClick: () => {
              this.clickEventFlag = true
              this.$refs['formPersonal'].validateField('mobileNo')
            },
            // 'mock': {
            //   'type': 'cardAccNumber'
            // },
            rules: [
              {
                required: true,
                message: '请输入预留手机号',
                trigger: 'blur'
              },
              {
                validator: validatePhone,
                trigger: 'blur'
              }
            ]
          },
          {
            label: '身份证号',
            prop: 'idNo',
            appendClick: () => {
              this.clickEventFlag = true
              this.$refs['formPersonal'].validateField('idNo')
            },
            // 'mock': {
            //   'type': 'idNum'
            // },
            rules: [
              {
                required: true,
                message: '请输入证件号码',
                trigger: 'blur'
              },
              {
                validator: validateIdCard,
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      idCheckTxt: '身份验证未通过',
      idPass: true,
      personalInfoData: {},
      defaultCustInfo: {
        custName: '--',
        gender: '--',
        age: '--',
        address: '--',
        mobileNo: '-',
        idNo: '-',
        idValidity: '--',
        ocpCdVal: '--',
        scdLvlOcpCdVal: '--'
      },
      personalOption: {},
      // 验密结果
      verificationResult: false
    }
  },
  created() {
    this._setParamsModule()
  },
  mounted() {
    // console.log('router name is ' + this.$route.name)
    const self = this
    // 验密结果
    window.eventEmitter.$on('EventVerifyResult', (data) => {
      console.log(data.i_verifyflag)
      if (data.i_verifyflag == '01') {
        self.$store.commit('SET_PERSONALFLAG', true)
        self.idCheckTxt = '身份验证通过'
        self.idPass = false
        self.verificationResult = true
      } else {
        self.$store.commit('SET_PERSONALFLAG', false)
        self.idCheckTxt = '身份验证未通过'
        self.idPass = true
        self.verificationResult = false
      }
    })
    // 振铃进线初始化
    window.eventEmitter.$on('EventCallRecordChange', () => {
      self.personalInfoData = self.defaultCustInfo
      self.$store.commit('SET_PERSONALFLAG', false)
      self.$store.commit('SET_OFFLINESTATUS', false)
      self.$store.commit('SET_PERSONALCHECKFLAG', false)
      self.$store.commit('SET_GLOBALCARDNO', '')
      self.idCheckTxt = '身份验证未通过'
      self.idPass = true
    })
    // 挂机初始化
    window.eventEmitter.$on('EventInfoReset', () => {
      self.personalInfoData = self.defaultCustInfo
      self.objForm = {}
      self.idCheckTxt = '身份验证未通过'
      self.idPass = true
      self.$store.commit('SET_PERSONALCHECKFLAG', false)
      self.$store.commit('SET_GLOBALCARDNO', '')
    })
  },
  methods: {
    // 数组排序
    sortArr(arr, str) {
      const _arr = []
      let _t = []
      let _tmp
      // 按时间排序 最新的在前面
      arr = arr.sort(function(a, b) {
        return Date.parse(b.createTime) - Date.parse(a.createTime)
      })
      // 按渠道名相同的排序
      arr = arr.sort(function(a, b) {
        var s = a[str]
        var t = b[str]
        return s < t ? -1 : 1
      })
      if (arr.length) {
        _tmp = arr[0][str]
      }
      for (var i in arr) {
        if (arr[i][str] === _tmp) {
          _t.push(arr[i])
        } else {
          _tmp = arr[i][str]
          _arr.push(_t)
          _t = [arr[i]]
        }
      }
      _arr.push(_t)
      return _arr
    },
    // 统计次数
    getTimes(arr, type) {
      const obj = {}
      // 单笔单批
      if (type == '1') {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].risCode == 'A') {
            if (obj[arr[i].channelName]) {
              obj[arr[i].channelName]++
            } else {
              obj[arr[i].channelName] = 1
            }
          }
        }
        // 其它
      } else if (type == '0') {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].isCallStatus == '1' && arr[i].risCode == 'A') {
            if (obj[arr[i].channelName]) {
              obj[arr[i].channelName]++
            } else {
              obj[arr[i].channelName] = 1
            }
          }
        }
      }
      const newArr = []
      for (const j in obj) {
        newArr.push(`${j} (${obj[j]}次)`)
      }
      const str = newArr.toString()
      return str
    },
    // 客户信息查询
    customerInquiry() {
      queryInfo(this.objForm)
        .then((res) => {
          if (res.data.code == '200') {
            this.personalInfoData = res.data.data
            if (this.objForm.mobileNo != this.personalInfoData.mobileNo) {
              this.personalInfoData.isRed = true
            }
            this.personalInfoData = res.data.data
            const creditList = res.data.data.creditList
            creditList.forEach(item => {
              // 渠道名称
              item.channelName = item.productName
              // 客户状态
              if (item.approveType == 'C') { item.approveType = '授信' } else if (item.approveType == 'V') { item.approveType = '用信' }
            })
            // 根据渠道来源分类
            const newCreditList = this.sortArr(creditList, 'channelName')
            // 统计客户状态
            const idValidity = []
            console.log(newCreditList)
            newCreditList.forEach(item => {
              const str = `${item[0].channelName}(${item[0].approveType})`
              if (item[0].channelName) { idValidity.push(str) }
            })
            this.personalInfoData.idValidity = idValidity.toString()
            // 授信渠道
            // 判断产品类别 isSingleApprove  0-否 1-是
            // 是否调用风控 isCallStatus     0-否 1-是
            // 单笔单批 risCode==A 授信次数+1 非单笔单批的 risCode==A  isCallStatus==1 授信次数+1
            const _newCreditList = this.sortArr(creditList, 'isSingleApprove')
            const ocpCdVal = []
            _newCreditList.forEach((item, index) => {
              if (this.getTimes(item, index)) {
                ocpCdVal.push(this.getTimes(item, index))
              }
            })
            if (ocpCdVal && ocpCdVal.length > 0) {
              this.personalInfoData.ocpCdVal = ocpCdVal.toString()
            } else {
              this.personalInfoData.ocpCdVal = '--'
            }
            // 用信状态
            // risCode ==A 次数+1
            const scdLvlOcpCdVal = []
            if (this.getTimes(creditList, 1)) {
              scdLvlOcpCdVal.push(this.getTimes(creditList, 1))
            }
            if (scdLvlOcpCdVal && scdLvlOcpCdVal.length > 0) {
              this.personalInfoData.scdLvlOcpCdVal = scdLvlOcpCdVal.toString()
            } else {
              this.personalInfoData.scdLvlOcpCdVal = '--'
            }
            sessionStorage.setItem(
              'personalInfoData',
              JSON.stringify(this.personalInfoData)
            )
            console.log(
              'response personalInfoData is: ' + JSON.stringify(res.data.data)
            )
          } else {
            // 无此客户信息恢复默认
            this.personalInfoData = this.defaultCustInfo
            window.globalUiKit.notify('提示', '查询无客户信息！', 'info')
            // 清除验证标识
            if (!this.$store.getters.GET_PERSONALFLAG) {
              this.$store.commit('SET_PERSONALFLAG', false)
              this.idCheckTxt = '身份验证未通过'
              this.idPass = true
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 跳转合同列表
    goCreditList(name) {
      // 验证通过后才可以跳转
      if (this.verificationResult) {
        this.$router.push({ name })
      } else {
        this.idCheckTxt = '身份验证未通过'
      }
    },
    // 模块参数化配置
    _setParamsModule() {
      this.personalOption = window.personalOptions.moduleOption.personalOption
      this.listData = window.personalOptions.routerQuery
      // console.log("personal router query array is: " + JSON.stringify(this.listData));
    },
    // 搜索框查询
    searchSubmitForm() {
      this.$message.success('当前数据' + JSON.stringify(this.objForm))
    },
    // 验密
    verificationFn(code) {
      const self = this
      if (!window.Settings.verifySwitch) {
        if (self.$store.getters.GET_OFFLINESTATUS) {
          window.globalUiKit.notify('提示', '离线状态不能验密！', 'error')
          return
        }
        // 如果客户信息存在才可以验证
        if (!self.personalInfoData) {
          window.globalUiKit.notify('提示', '客户信息不存在！', 'error')
          return
        }
      } else {
        self.$store.commit('SET_PERSONALFLAG', true)
      }
      // 判断是哪种验证方式
      window.globalUiKit.confirm(
        '提示',
        '是否要进行电话验密操作?',
        function() {
          // 密码验证
          if (code == '0') {
            const userdata = {
              // 私有部分，根据不同验证类型组合
              p_verifytype: '01', // 验密类型  01：电话验密  02：短信验密
              p_cert_type: '01', // 介质类型   01：进线手机号
              p_cert_num: self.personalInfoData.mobileNo || '', // 介质号码
              p_accno: '', // 对公客户号
              p_oper_id: '', // 对公操作员ID
              p_pass_type: '01', // 密码类型
              p_pass_operate: '01', // 交易密码操作
              p_biz: '00', // 业务操作
              // 公共部分
              r_function: 'singletransfer',
              r_flag: '3',
              con_flag: '1'
            }
            globalUserData.verifyPass(userdata)
          } else {
            console.log('准备短信验证')
            // 短信验证
            // 发送短信验证
            const data = { mobileNo: self.personalInfoData.mobileNo }
            sendCode(data).then(res => {
              if (res.data.code == '200') {
                console.log('已发送短信验证')
                const userdata = {
                  // 私有部分，根据不同验证类型组合
                  p_verifytype: '02', // 验密类型  01：电话验密  02：短信验密
                  p_cert_type: '01', // 介质类型   01：进线手机号
                  p_cert_num: self.personalInfoData.mobileNo || '', // 介质号码
                  p_ccsCode: res.data.data.ccsCode, // 短信流水号
                  p_accno: '', // 对公客户号
                  p_oper_id: '', // 对公操作员ID
                  p_pass_type: '01', // 密码类型
                  p_pass_operate: '01', // 交易密码操作
                  p_biz: '00', // 业务操作
                  // 公共部分
                  r_function: 'singletransfer',
                  r_flag: '3',
                  con_flag: '1'
                }
                globalUserData.verifyPass(userdata)
              }
            })
          }
          if (window.Settings.verifySuccessSwitch) {
            self.$store.commit('SET_PERSONALFLAG', true)
            self.idCheckTxt = '身份验证通过'
            self.idPass = false
          }
        }
      )
    },
    // 按钮搜索条件，请求方法集合
    allFn() {
      // 离线状态不能操作
      if (this.$store.getters.GET_OFFLINESTATUS) {
        window.globalUiKit.notify('提示', '离线状态不能查询！', 'error')
        return
      }
      this.customerInquiry()
    }
  },
  // 路由拦截
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      console.log('personal bank no is: ' + vm.personalBankNo)
      if (vm.personalBankNo) {
        sessionStorage.setItem('bankNo', vm.personalBankNo)
      } else {
        sessionStorage.setItem('bankNo', '')
      }
    })
  }
}
</script>
<style scoped>
.custInfo .el-col span,
.cardAndAccInfo .el-col span {
  line-height: 34px;
}

.bankNameSelect .el-select .el-input.is-focus .el-input__inner {
  border-color: #b50029 !important;
}

/*子模块区域*/
.inlineStyle {
  width: 100px;
  display: inline-block;
  text-align: center;
}

.inlineStyle span {
  text-align: center;
  display: block;
}

.sonArea img {
  width: 70px;
  height: 70px;
}

.el-dialog tr > th.el-table_1_column_1 > .cell {
  display: none;
}

/*超出省略*/
.wordEllipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  white-space: nowrap;
}

.bankContainer .el-form-item {
  margin-bottom: 6px;
}

.bankContainer ul li {
  float: none !important;
  text-align: left !important;
}

.topHeaderSearch span {
  height: 40px;
  line-height: 40px;
}

.searchInputStyle {
  color: #606266;
  font-weight: 700;
  line-height: 34px;
}

.verificationTips {
  width: 100%;
  height: 1px;
  text-align: right;
  position: relative;
}

.verificationTips span {
  position: absolute;
  right: 10px;
  top: 15px;
  z-index: 99;
}
</style>
